/**
 * Created with JetBrains PhpStorm.
 * User: Alex
 * Date: 9/28/13
 * Time: 2:55 PM
 * To change this template use File | Settings | File Templates.
 */


var GamePage = function ()
{
	var WebPage = null;

	var GivenAnswer = {
		"Undefined": -1,
		"Yes": 0,
		"No": 1,
		"DontKnow": 2,
		"ProbablyYes": 3,
		"ProbablyNo": 4
	};

	var ResponseType = {
		"Question": 1,
		"Result": 2
	}

	var Data = {};
	Data.GameId = null;
	Data.QuestionIndex = 0;
	Data.LastGivenAnswer = GivenAnswer.Undefined;
	Data.SelectedObjectName = "";

	var Controls = {};
	Controls.btnAnswerYes = null;
	Controls.btnAnswerNo = null;
	Controls.btnAnswerDontKnow = null;
	Controls.btnAnswerProbablyYes = null;
	Controls.btnAnswerProbablyNo = null;
	Controls.gridQuestionList = null;
	Controls.tmplQuestion = null;
	Controls.tmplResponse = null;
	Controls.tmplTopGuesses = null;
	Controls.txtObjectName = null; // used for autocomplete - in case the system does not guess and the user wants to upload the object he thought of

	this.initializeControls = function ()
	{
		WebPage = new PHP.WebPage();

		Data.GameId = $("#idGame").val(); // will be taken later from a hidden field.

		getNextQuestion(GivenAnswer.Undefined);

		Controls.tmplQuestion = $("#tmplQuestion");
		Controls.tmplResponse = $("#tmplResponse");
		Controls.tmplTopGuesses = $("#tmplTopGuesses");

		initializeAnswerButtons();

		Controls.gridQuestionList = $("#gridQuestionList");
		Controls.wrapperResponse = $("#wrapper-response");

		if (Controls.gridQuestionList.length <= 0)
		{
			throw  "gridQuestionList.notFoundException";
		}

		$("#wrapper-top-guesses").delegate("a", "click", function ()
		{
			var id = $(this).data("id");
			var name = $(this).data("name");

			sendSelectedGuess(id, name);
		});

		Controls.txtObjectName = $("#txtObjectName");
		if (Controls.txtObjectName.length > 0)
		{
			Controls.txtObjectName.preventSubmit();
			Controls.txtObjectName.autocomplete({
				source: function (request, response)
				{
					Controls.txtObjectName.data({ "ObjectId": -1 });
					WebPage.ajaxCall(
						"autocomplete.php",
						{
							"prefix": Controls.txtObjectName.val()
						},
						function (data)
						{
							response($.map(data, function (item)
							{
								return { ID: item.ObjectId, label: item.Name }
							}))
						});
				},
				minLength: 3,
				select: function (event, ui)
				{
					if (ui && ui.item)
					{
						Controls.txtObjectName.data({ "ObjectId": ui.item.ID });
					}
				},
				close: function ()
				{
					if (Controls.txtObjectName.data().ObjectId == -1)
					{
						//Controls.txtObjectName.val("");
					}
				}
			});
		}
	};

	var getNextQuestion = function (answer)
	{
		Data.LastGivenAnswer = answer;

		WebPage.ajaxCall(
			'nextquestion.php',
			{
				gameid: Data.GameId,
				answer: answer
			},
			manageResponseType,
			{
				"debugMode": false,
				"showAjaxRoller": true
			});
	};

	var initializeAnswerButtons = function ()
	{
		Controls.btnAnswerYes = $("#btnAnswerYes");
		if (Controls.btnAnswerYes.length > 0)
		{
			Controls.btnAnswerYes.click(function ()
			{
				getNextQuestion(GivenAnswer.Yes);
			});
		}
		else
		{
			throw  "btnAnswerYes.notFoundException";
		}
		Controls.btnAnswerNo = $("#btnAnswerNo");
		if (Controls.btnAnswerNo.length > 0)
		{
			Controls.btnAnswerNo.click(function ()
			{
				getNextQuestion(GivenAnswer.No);
			});
		}
		else
		{
			throw  "btnAnswerNo.notFoundException";
		}
		Controls.btnAnswerDontKnow = $("#btnAnswerDontKnow");
		if (Controls.btnAnswerDontKnow.length > 0)
		{
			Controls.btnAnswerDontKnow.click(function ()
			{
				getNextQuestion(GivenAnswer.DontKnow);
			});
		}
		else
		{
			throw  "btnAnswerDontKnow.notFoundException";
		}
		Controls.btnAnswerProbablyYes = $("#btnAnswerProbablyYes");
		if (Controls.btnAnswerProbablyYes.length > 0)
		{
			Controls.btnAnswerProbablyYes.click(function ()
			{
				getNextQuestion(GivenAnswer.ProbablyYes);
			});
		}
		else
		{
			throw  "btnAnswerProbablyYes.notFoundException";
		}
		Controls.btnAnswerProbablyNo = $("#btnAnswerProbablyNo");
		if (Controls.btnAnswerProbablyNo.length > 0)
		{
			Controls.btnAnswerProbablyNo.click(function ()
			{
				getNextQuestion(GivenAnswer.ProbablyNo);
			});
		}
		else
		{
			throw  "btnAnswerProbablyNo.notFoundException";
		}
	};

	var loadPreviousQuestionAnswer = function ()
	{
		var lastGivenAnswerString = '';
		if (Data.LastGivenAnswer != GivenAnswer.Undefined && Data.QuestionIndex > 0)
		{
			lastGivenAnswerString = GivenAnswerString(Data.LastGivenAnswer);
			Controls.gridQuestionList.find("#question" + (Data.QuestionIndex)).text(lastGivenAnswerString);

			// after we load the answer for the previous question we also show the question in the grid
			Controls.gridQuestionList.find(".record").show();
		}
	};

	var manageResponseType = function (data)
	{
		if (data)
		{
			switch (data.ResponseType)
			{
				case ResponseType.Question:
				{
					manageResponseTypeQuestion(data);
				}
					break;
				case ResponseType.Result:
				{
					manageResponseTypeResult(data);
				}
					break;
				default :
					$("html").empty();
			}
		}
	};

	var manageResponseTypeQuestion = function (data)
	{
		loadPreviousQuestionAnswer();

		var question = {};

		question.QuestionIndex = Data.QuestionIndex + 1;
		question.Question = data.Question;
		question.par = (Data.QuestionIndex % 2) == 0 ? " par" : "";

		Controls.tmplQuestion.tmpl(question).appendTo(Controls.gridQuestionList.find(".records"));

		Data.QuestionIndex += 1;

		$(".current_question_content").text(data.Question);
		$("#current_questions_number").text(Data.QuestionIndex);
	};

	var manageResponseTypeResult = function (data)
	{
		loadPreviousQuestionAnswer();

		var response = {};
		response.ObjectName = data.ObjectName;

		Data.SelectedObjectName = data.ObjectName;
		Data.ObjectId = data.ObjectId;

		Controls.tmplResponse.tmpl(response).appendTo(Controls.wrapperResponse); // load the response
		Controls.wrapperResponse.show(); // show the response


		$("#btnCorrectAnswer").click(function ()
		{
			manageFeedback(true);

			$(".play_again").show();
		});
		$("#btnIncorrectAnswer").click(function ()
		{
			manageFeedback(false);
		});

		// hide unused controls
		$("#wrapper-possible-answers").hide(); // we hide the answer buttons -> game has finished, user can't send any answers
		$(".current_question_number").hide();
		$(".current_question_content").hide();
	};

	var manageFeedback = function (result)
	{
		if (result)
		{
			manageFeedbackAcceptAnswer();
		}
		else
		{
			manageFeedbackRejectAnswer();
		}
	};

	var manageFeedbackAcceptAnswer = function ()
	{
		WebPage.ajaxCall(
			"correct.php",
			{
				"gameid": Data.GameId,
				"objectid" : Data.ObjectId
			},
			function (data)
			{
				$("#feedback_buttons").hide(); // asnwer was correct - we hide the feedback buttons
				$("#feedback_accepted_amswer_machine_message").show(); // asnwer was correct - we show the system message

				loadExpectedAnswerList(data);
			},
			{
				"debugMode": false,
				"showAjaxRoller": true
			});
	};

	var manageFeedbackRejectAnswer = function ()
	{
		WebPage.ajaxCall(
			"incorrect.php",
			{
				"gameid": Data.GameId
			},
			function(data)
			{
				if (data)
				{
					$("#wrapper-response").hide();

					var wrapperTopGuesses = $("#wrapper-top-guesses");
					var k;
					for (k = 0; k < data.length; k++)
					{
						var guess = {};
						guess.Index = (k + 1);
						guess.ObjectId = data[k].ObjectId;
						guess.Name = data[k].Name;
						guess.Dot = '. ';
						guess.Class = 'top_guesses_link';

						Controls.tmplTopGuesses.tmpl(guess).appendTo(wrapperTopGuesses);
					}

					var additionalGuess = {};
					additionalGuess.ObjectId = -1;
					additionalGuess.Name = "No, none of these.";
					additionalGuess.Class = 'none_of_top_guesses_link';

					Controls.tmplTopGuesses.tmpl(additionalGuess).appendTo(wrapperTopGuesses);

					wrapperTopGuesses.show();

					$("#feedback_buttons").hide(); // we hide the feedback buttons
					$("#feedback-sorry-message").show(); // we show a sorry feedback message to the user
				}
			},
			{
				"debugMode": false,
				"showAjaxRoller": true
			});
	};

	var sendSelectedGuess = function (id, name)
	{
		Controls.wrapperResponse.hide();

		if (id > 0)
		{
			WebPage.ajaxCall(
				"incorrectupdate.php",
				{
					"gameid": Data.GameId,
					"objectid": id
				},
				function(data)
				{
					if (data)
					{
						// we show a message to the user with the choice he picked and a thank you message

						$("#selected-top-guess") // wrapper for the selected top guess
							.empty()
							.append(
								$('<span class="guessed_object"></span>')
									.text(name)
							)
							.append(
								$("<p></p>")
									.text("Great feedback!") // the thank you message
							)
							.show();

						$("#wrapper-top-guesses").hide(); // we hide the top guesses list because the user has selected the right answer.

						Data.SelectedObjectName = name;
						loadExpectedAnswerList(data);

						$(".play_again").show();
					}
				},
				{
					"debugMode": false,
					"showAjaxRoller": true
				});
		}
		else
		{
			$("#wrapper-top-guesses").hide(); // we hide the top guesses list because the user has selected the right answer.

			// we show a grid where the user can set the correct answer
			// the user will be provided with an autocomplete which will load object names from database
			// if none of the object names loaded from the database match the user`s thought object, he can submit his as well.
			$("#divUserInputAnswer").show();

			$("#btnSubmitAddNew").click(function()
			{
				var selectedObjectID = Controls.txtObjectName.data().ObjectId;
				if(selectedObjectID <= 0)
				{
					selectedObjectID = -1;
				}

				WebPage.ajaxCall(
					"addnew.php",
					{
						"gameid": Data.GameId,
						"objectid": selectedObjectID,
						"objectname": Controls.txtObjectName.val()
					},
					function(data)
					{
						Data.SelectedObjectName = Controls.txtObjectName.val();

						loadExpectedAnswerList(data);

						// hide the submit button
						// unbind the click event from the submit button so the user cannot use it again
						$("#btnSubmitAddNew").hide().unbind("click");

						// we hide the textbox after we finished the insertion
						Controls.txtObjectName.hide();

						$("#divUserInputAnswer")
							.empty()
							.append(
								$('<span class="guessed_object"></span>')
									.text(Controls.txtObjectName.val())
							)
							.append(
								$("<p></p>")
									.text("Object successfully added.")
							);

						$(".play_again").show();
					},
					{
						"debugMode": false,
						"showAjaxRoller": true
					})
			});
		}
	};

	var GivenAnswerString = function (givenAnswer)
	{
		var givenAnswerString = "";
		switch (givenAnswer)
		{
			case GivenAnswer.Yes:
			{
				givenAnswerString = "Yes";
			}
				break;
			case GivenAnswer.No:
			{
				givenAnswerString = "No";
			}
				break;
			case GivenAnswer.DontKnow:
			{
				givenAnswerString = "Don't know";
			}
				break;
			case GivenAnswer.ProbablyYes:
			{
				givenAnswerString = "Probably yes";
			}
				break;
			case GivenAnswer.ProbablyNo:
			{
				givenAnswerString = "Probably no";
			}
				break;
		}

		return givenAnswerString;
	}

	var loadExpectedAnswerList = function(data)
	{
		if (data && data.length && data.length > 0)
		{
			var k;
			for (k = 0; k < data.length; k++)
			{
				var expectedAnswer = data[k];
				$("#expectedAnswer" + (k + 1)).text(GivenAnswerString(expectedAnswer));
			}
		}
	}
};